"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008  Obol Software Pty Ltd

This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt

"""

import phunc.info as info
import phunc.cx_wrapper.db_tools as db_tools
from phunc.logger import logger

##def cryptPasswd( passwd,oldpasswd = None ):
##        """
##        Encrypt the passwd.
##        """
##        hashCode='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
##        import random
##        import crypt
##        if oldpasswd == None:
##                hashedPasswd = random.choice( hashCode ) + random.choice( hashCode )
##        else:
##                hashedPasswd = oldpasswd[:2]
##        return crypt.crypt( passwd , hashedPasswd )

def createUser( conn, name, passwd ):
        """
        Create a user, return an error if name exists
        """
        cursor = conn.cursor()
        broadcast_message = None
        logger .debug('name:%s  passwd:%s' % (name,passwd) )
        isUserExist = db_tools.exec_action( cursor,'app_get_user_info',[name])
        if not isUserExist:
                userid = int(db_tools.exec_action(cursor, 'get_system_user_id')[0]['id'])
                db_tools.exec_action( cursor,'insert_user',[userid,name,passwd])
                broadcast_message = "User '%s' created successfully. "%name
        else:
                if not isUserExist[0]['is_active']:
                        db_tools.exec_action( cursor,'active_user',[ passwd, isUserExist[0]['id']])
                        broadcast_message = "User '%s' created successfully. "%name
                else:
                        broadcast_message = "User '%s' alread exists. "%name
                userid = int(isUserExist[0]['id'])
        conn.commit()
        return (userid, broadcast_message)
    
def grantUser( conn, user_id, company_id, group_id ):
        """
        Assign company, group to user.
        """
        cursor = conn.cursor()
        isAffiliationExist = db_tools.exec_action( cursor,'app_get_user_affiliation',[user_id,company_id,group_id])
        if not isAffiliationExist:
                same_rights = db_tools.exec_action(cursor, 'user_have_right', [user_id,int(company_id)])
                if same_rights:
                        company_name = db_tools.exec_action(cursor, 'get_company_name', [int(company_id)])[0]['name']
                        broadcast_message ="'%s' can not have more than one role on '%s'!"%(name,company_name)
                        return broadcast_message
                db_tools.exec_action(cursor,'assign_user',[user_id,company_id,group_id])
                affiliation = db_tools.exec_action( cursor,'app_get_user_affiliation',[user_id,company_id,group_id])
                broadcast_message = "'%s' as '%s' on '%s' authorize successfully"%(affiliation[0]['user_name'],affiliation[0]['group_name'],affiliation[0]['company_name'])
        else:
                broadcast_message = "'%s' as '%s' on '%s' had been authorized already"%(isAffiliationExist[0]['user_name'],isAffiliationExist[0]['group_name'],isAffiliationExist[0]['company_name'])
        conn.commit()
        return broadcast_message 
        
def changePasswd( cursor, name, oldPasswd, newPasswd ):
        """
        Change a user's password, returning appropriate errors
        """
        broadcast_message = None
        user_list = db_tools.exec_action( cursor,'app_get_user_info',[name])
        isUserExist = len( user_list ) > 0
        if isUserExist:
                if len(db_tools.exec_action(cursor, 'app_verify_user_passwd',[name,oldPasswd])) > 0:
                        db_tools.exec_action(cursor, 'app_update_user_passwd',(newPasswd, name) )
                        broadcast_message = "User '%s' password changed"%name
                else:
                        broadcast_message = 'Old Password not correct'
        else:
                broadcast_message = "User '%s' is not exist"%name

        return broadcast_message 

def getUserAccess( cursor, user, company_id ):
        '''
            get user's role
        '''
        retset = db_tools.exec_action( cursor,'app_get_user_role',[user,company_id])
        roleset = []
        if len( retset ) > 0 :
                for r in retset:
                        roleset.append( r['rolename'] )
        return roleset
